package com.qiuzhiyi.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.li.utils.TransformUtil;
import com.li.widget.DoubleTextView;
import com.li.widget.TopNavigationBar;
import com.qiuzhiyi.R;
import com.qiuzhiyi.base.QZYBaseActivity;
import com.qiuzhiyi.cache.HumanCache;
import com.qiuzhiyi.item.AboutUsItem;
import com.qiuzhiyi.item.BaseItem;
import com.qiuzhiyi.item.ZhaoGongDetailItem;
import com.qiuzhiyi.net.ObservableHelper;
import com.qiuzhiyi.net.RetrofitHelper;
import com.qiuzhiyi.net.SelectorObserver;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Author: Li
 * Date: 2017/11/16 0016
 * Description: 工作详情
 */

public class JobDetailActivity extends QZYBaseActivity implements View.OnClickListener {

    private static final int CHOOSE_AGENT_CODE = 1;
    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.txt_fuli)
    TextView mTxtFuli;
    @BindView(R.id.txt_address)
    TextView mTxtAddress;
    @BindView(R.id.layout_content)
    LinearLayout mLayoutContent;
    @BindView(R.id.txt_intro)
    TextView mTxtIntro;
    @BindView(R.id.img_head)
    ImageView mImgHead;
    @BindView(R.id.txt_show_history)
    TextView mTxtShowHistory;
    private int[] mLocation = new int[2];
    private AlertDialog mDialog;
    private SparseArray<Class> mSparseArray;
    private ZhaoGongDetailItem.LinkmanBean mLinkmanBean;
    private ZhaoGongDetailItem mDetailItem;
    private String mCompanyId;
    private String mType;
    private String mSalary;
    private String mName;
    private BottomSheetDialog mBottomSheetDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_job_detail;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        mSparseArray = new SparseArray<>();
        mSparseArray.put(R.id.txt_salary, SalaryActivity.class);
        mSparseArray.put(R.id.txt_post, PostActivity.class);
        mSparseArray.put(R.id.txt_agent, AgentActivity.class);
//        mSparseArray.put(R.id.txt_tiwen, TiWenActivity.class);
//        mSparseArray.put(R.id.txt_fatie, FaTieActivity.class);

        mCompanyId = getIntent().getStringExtra("id");
        mType = getIntent().getStringExtra("type");
        mSalary = getIntent().getStringExtra("salary");
        mName = getIntent().getStringExtra("name");
        showDetail(mCompanyId);

    }

    /**
     * 弹出分享面板
     *
     * @param view view
     */
    @Override
    public void onFunctionImgListener(View view) {
        super.onFunctionImgListener(view);
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.setType("text/*");
        sendIntent.putExtra(Intent.EXTRA_TEXT, mName);
        startActivity(sendIntent);
    }

    @OnClick({R.id.txt_fuli, R.id.txt_salary, R.id.txt_post, R.id.txt_agent,
            R.id.txt_baoming, R.id.txt_zixun, R.id.txt_history})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            //报名
            case R.id.txt_baoming:
                if (mDetailItem == null) {
                    showToast("请等页面加载完成");
                    return;
                }
                mItem = HumanCache.getHumanInfo(mContext);
                if (mItem == null) {
                    mUid="";
                }else {
                    mUid=String.valueOf(mItem.getHumanId());
                }
                if (TextUtils.isEmpty(mUid)) {
                    start(LoginActivity.class);
                    return;
                }
                new QMUIDialog.MessageDialogBuilder(mContext)
                        .setTitle("提示")
                        .setMessage("报名时请选择您的经纪人")
                        .addAction("取消", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                            }
                        })
                        .addAction("确定", new QMUIDialogAction.ActionListener() {
                            @Override
                            public void onClick(QMUIDialog dialog, int index) {
                                dialog.dismiss();
                                Bundle bundle = new Bundle();
                                bundle.putString("op", "chooseAgent");
                                Intent intent = new Intent(mContext, AgentActivity.class);
                                intent.putExtras(bundle);
                                startActivityForResult(intent, CHOOSE_AGENT_CODE);

                            }
                        }).create().show();
                break;
            //福利
            case R.id.txt_fuli:
//                showFuliPop();
                if (mDetailItem != null) {
                    Bundle bundle = new Bundle();
                    ArrayList<String> list = new ArrayList<>();
                    for (ZhaoGongDetailItem.HspicturesBean hspicturesBean : mDetailItem.getHspictures()) {
                        list.add(hspicturesBean.getPictureUrl());
                    }
                    //图片
                    bundle.putStringArrayList("foodPic", list);
                    //伙食信息
                    bundle.putString("foodFee", mDetailItem.getCQq());
                    //住宿信息
                    bundle.putString("live",mDetailItem.getCWeibo());
                    //其他信息
                    bundle.putString("foodRemind", mDetailItem.getCTrde());
                    startWithArg(HuoShiActivity.class, bundle);
                } else {
                    showToast("暂未录入伙食情况");
                }
                break;
            //岗位
            case R.id.txt_post:
                if (mLinkmanBean != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("jobType", mLinkmanBean.getLmName());
                    bundle.putString("jobContent", mLinkmanBean.getLmPhone3());
                    bundle.putString("jobEnv", mLinkmanBean.getLmEmail());
                    bundle.putString("jobTime", mLinkmanBean.getLmPost());
                    bundle.putString("jobRemind", mLinkmanBean.getLmQq());
                    ArrayList<String> list = new ArrayList<>();
                    for (ZhaoGongDetailItem.JobpicturesBean jobpicturesBean : mDetailItem.getJobpictures()) {
                        list.add(jobpicturesBean.getPictureUrl());
                    }
                    bundle.putStringArrayList("jobPic", list);
                    startWithArg(PostActivity.class, bundle);
                } else {
                    showToast("暂未录入岗位信息");
                }
                break;
            //薪资
            case R.id.txt_salary:
                if (mDetailItem != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("salaryTime", mDetailItem.getCJob());
                    bundle.putString("salaryCalWay", mDetailItem.getCScale());
                    startWithArg(SalaryActivity.class, bundle);
                } else {
                    showToast("暂未录入薪资信息");
                }

                break;
            case R.id.txt_zixun:
                getAboutUsInfo();
                break;
//            case R.id.txt_tiwen:
//                if (mDetailItem == null) {
//                    showToast("请等页面加载完成");
//                    return;
//                }
//                Bundle bundle=new Bundle();
//                bundle.putString("title",mDetailItem.getCName());
//                startWithArg(TiWenActivity.class,bundle);
//                break;
            case R.id.txt_history:
                Bundle bundle = new Bundle();
                bundle.putString("id", mCompanyId);
                startWithArg(FeeHistoryActivity.class, bundle);
                break;
            default:
                start(mSparseArray.get(v.getId()));
                break;
        }
    }

    private void showBottom(String wx, String qq, final String phone) {
        DoubleTextView txtWx = null;
        DoubleTextView txtQQ = null;
        DoubleTextView txtOfficial = null;
        if (mBottomSheetDialog == null) {
            mBottomSheetDialog = new BottomSheetDialog(mContext);
            mBottomSheetDialog.setCanceledOnTouchOutside(false);
            View view = LayoutInflater.from(mContext).inflate(R.layout.layout_bottom_zixun, null);
            txtWx = view.findViewById(R.id.txt_wx);
            txtQQ = view.findViewById(R.id.txt_qq);
            txtOfficial = view.findViewById(R.id.txt_official);

            view.findViewById(R.id.txt_confirm).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mBottomSheetDialog != null) {
                        mBottomSheetDialog.dismiss();
                    }
                }
            });
            txtWx.setTxtRight("123465");
            txtQQ.setTxtRight("123456");
            txtOfficial.setTxtRight("123456");
            txtOfficial.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(Intent.ACTION_DIAL);
                    intent.setData(Uri.parse("tel:"+phone));
                    startActivity(intent);
                }
            });
            mBottomSheetDialog.setContentView(view);
        }
        if (txtWx != null) {
            txtWx.setTxtRight(wx);

        }
        if (txtQQ != null) {
            txtQQ.setTxtRight(qq);
        }
        if (txtOfficial != null) {
            txtOfficial.setTxtRight(phone);
        }
        mBottomSheetDialog.show();
    }

    /**
     * 显示福利弹窗
     */
    private void showFuliPop() {
        if (mDialog == null) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.layout_fuli, null);
            view.findViewById(R.id.txt_zhusu).setOnClickListener(this);
            view.findViewById(R.id.txt_huoshi).setOnClickListener(this);
            mTxtFuli.measure(0, 0);
            view.measure(0, 0);
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext)
                    .setView(view);
            mDialog = builder.create();
        }
        mTxtFuli.getLocationInWindow(mLocation);
        mDialog.show();
        Window window = mDialog.getWindow();
        if (window == null) {
            return;
        }
        int width = TransformUtil.dp2px(mContext, 100);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.START | Gravity.TOP;
        params.width = width;
        params.x = mLocation[0] - width - TransformUtil.dp2px(mContext, 10);
        params.y = mLocation[1] - mTxtFuli.getMeasuredHeight() / 2;
        window.setAttributes(params);
    }

    @Override
    public void onClick(View v) {
        mDialog.dismiss();
        switch (v.getId()) {
            case R.id.txt_zhusu:

                if (mDetailItem != null) {
                    Bundle bundle = new Bundle();
                    ArrayList<String> list = new ArrayList<>();
                    for (ZhaoGongDetailItem.PicturesBean picturesBean : mDetailItem.getPictures()) {
                        list.add(picturesBean.getPictureUrl());
                    }
                    bundle.putStringArrayList("livePic", list);
                    bundle.putString("liveLocation", mDetailItem.getCWeibo());
                    bundle.putString("liveEnv", mDetailItem.getCAddress());
                    bundle.putString("liveFee", mDetailItem.getCSite());
                    bundle.putString("liveCar", mDetailItem.getCHotel());
                    bundle.putString("liveRemind", mDetailItem.getCWechat());
                    startWithArg(ZhuSuActivity.class, bundle);
                } else {
                    showToast("暂未录入住宿信息");
                }

                break;
            case R.id.txt_huoshi:
                if (mDetailItem != null) {
                    Bundle bundle = new Bundle();
                    ArrayList<String> list = new ArrayList<>();
                    for (ZhaoGongDetailItem.HspicturesBean hspicturesBean : mDetailItem.getHspictures()) {
                        list.add(hspicturesBean.getPictureUrl());
                    }
                    //图片
                    bundle.putStringArrayList("foodPic", list);
                    //伙食信息
                    bundle.putString("foodFee", mDetailItem.getCQq());
                    //住宿信息
                    bundle.putString("live",mDetailItem.getCWeibo());
                    //其它信息
                    bundle.putString("foodRemind", mDetailItem.getCTrde());
                    startWithArg(HuoShiActivity.class, bundle);
                } else {
                    showToast("暂未录入福利信息");
                }
                break;
        }
    }

    /**
     * 显示详情
     *
     * @param id 公司编号
     */
    private void showDetail(String id) {
        Map<String, String> map = new HashMap<>();
        map.put("cId", id);
        ObservableHelper.createObservable(RetrofitHelper.createService().showZhaogongDetail(map))
                .subscribe(new SelectorObserver<BaseItem<ZhaoGongDetailItem>>() {
                    @Override
                    protected void onErrorCodeInfo(String code, String info) {
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseItem<ZhaoGongDetailItem> item) {
                        ZhaoGongDetailItem detailItem = item.getObjValue();
                        mDetailItem = detailItem;
                        mLinkmanBean = detailItem.getLinkman();
                        mTopNavigation.setTitle(detailItem.getCName());
                        Glide.with(mContext).load(detailItem.getCBirth()).error(R.mipmap.icon).into(mImgHead);
                        mTxtAddress.setText(detailItem.getCArea());
                        mTxtIntro.setText(detailItem.getCRemark());
                        mTxtShowHistory.setText(detailItem.getCAddress());
                        for (ZhaoGongDetailItem.JobpicturesBean picturesBean : detailItem.getJobpictures()) {
                            ImageView imageView = new ImageView(mContext);
                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                    TransformUtil.dp2px(mContext, 150), TransformUtil.dp2px(mContext, 70)
                            );
                            imageView.setLayoutParams(params);
                            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            Glide.with(mContext).load(picturesBean.getPictureUrl())
                                    .error(R.mipmap.icon).into(imageView);
                            mLayoutContent.addView(imageView);

                        }
                    }

                    @Override
                    protected void onFinish() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog();
                    }
                });
    }

    /**
     * 报名
     *
     * @param oHumanId   会员id
     * @param oHumanName 会员账号
     * @param oCompanyId 公司Id
     * @param oCompany   公司名称
     * @param oJob       工作性质 1：全职 2：兼职
     * @param salary     薪资 分月薪和日薪
     * @param oEmpId     经纪人id
     * @param oUsername  经纪人姓名
     */
    private void signUp(String oHumanId, String oHumanName, String oCompanyId,
                        String oCompany, String oJob, String salary, String oEmpId, String oUsername) {


        Map<String, String> map = new HashMap<>();
        map.put("oHumanId", oHumanId);
        map.put("oHumanName", oHumanName);
        map.put("oCompanyId", oCompanyId);
        map.put("oCompany", oCompany);
        map.put("oJob", oJob);
        map.put("oEmpId", oEmpId);
        map.put("oUsername", oUsername);
        switch (oJob) {
            case "1":
                map.put("oJobSalary", salary);
                break;
            case "2":
                map.put("oJobSalaryDay", salary);
                break;
        }
        ObservableHelper.createObservable(RetrofitHelper.createService().signUp(map))
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog("正在报名");
                    }

                    @Override
                    public void onNext(String s) {
                        try {
                            JSONObject object = new JSONObject(s);
                            String code = object.getString("code");
                            switch (code) {
                                case "200":
                                    showToast("报名成功");
                                    break;
                                default:
                                    showToast("报名失败");
                                    break;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            showToast("报名失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingDialog();
                        showToast("报名失败");
                    }

                    @Override
                    public void onComplete() {
                        dismissLoadingDialog();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CHOOSE_AGENT_CODE) {
            if (resultCode == RESULT_OK) {
                String empId = data.getStringExtra("empId");
                String empName = data.getStringExtra("empName");
                signUp(mUid, mItem.getHumanAccount(), mCompanyId, mName, mType, mSalary, empId, empName);
            } else {
                showToast("报名时必须选择经纪人，否则无法报名");
            }
        }
    }

    private void getAboutUsInfo() {
        ObservableHelper.createObservable(RetrofitHelper.createService().getAboutUsInfo())
                .subscribe(new SelectorObserver<BaseItem<AboutUsItem>>() {
                    @Override
                    protected void onErrorCodeInfo(String code, String info) {
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseItem<AboutUsItem> item) {

                        showBottom(item.getObjValue().getCompany_fax(),
                                item.getObjValue().getCompany_qq(),
                                item.getObjValue().getCompany_phone());
                    }

                    @Override
                    protected void onFinish() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog();
                    }
                });
    }
}